//
//  BQOrderViewController.m
//  BeeQuick
//
//  Created by Vivitickey on 2017/4/26.
//  Copyright © 2017年 test. All rights reserved.
//

#import "BQOrderViewController.h"
#import "BQLeftModel.h"
#import "BQRightModel.h"
#import "BQLeftCell.h"
#import "BQRightCell.h"
#import "UIColor+HMAddition.h"
@interface BQOrderViewController ()<UITableViewDelegate, UITableViewDataSource>


@property (nonatomic, weak) UITableView *leftTableView;

@property (nonatomic, weak) UITableView *rightTableView;

@end

/**
 重用标识符
 */

static NSString *left_id = @"left_id";

static NSString *right_id = @"right_id";

@implementation BQOrderViewController{
    
    NSArray *_leftArray;
    
    NSArray *_rightArray;
    
}

#pragma mark - 购物车数据
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    
}

-(void)setupUI{
    [super setupUI];
    
    self.navigationController.navigationBar.barTintColor = [UIColor hm_colorWithR:252 G:207 B:47];
    
    //左侧tableView
    UITableView *leftTableView = [[UITableView alloc] init];
    
    _leftTableView = leftTableView;
    
    leftTableView.backgroundColor = [UIColor hm_colorWithR:236 G:236 B:236];
    
    leftTableView.dataSource = self;
    leftTableView.delegate = self;
    
    [self.view addSubview:leftTableView];
    
    // 注册cell
    [leftTableView registerClass:[BQLeftCell class] forCellReuseIdentifier:left_id];
    
    // 设置约束
    [leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.bottom.equalTo(self.view);
        
        make.width.mas_equalTo(100);
        
    }];
    
    leftTableView.tableFooterView = [UIView new];
    
    
    //右侧tableView
    UITableView *rightTableView = [[UITableView alloc] init];
    
    _rightTableView = rightTableView;
    
    rightTableView.dataSource = self;
    rightTableView.delegate = self;
    
    // 设置自动计算行高
    
    rightTableView.rowHeight = 80;
    
    
    [self.view addSubview:rightTableView];
    
    UINib *nib = [UINib nibWithNibName:@"BQRightCell" bundle:nil];
    
    [rightTableView registerNib:nib forCellReuseIdentifier:right_id];
    
    // 设置约束
    [rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.view);
        
        make.left.equalTo(leftTableView.mas_right);
        
        make.top.equalTo(self.view).offset(64);
        
        make.bottom.equalTo(self.view).offset(-44);
        
    }];
    
    rightTableView.tableFooterView = [UIView new];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == _leftTableView) {
        
        return _leftArray.count;
        
    } else {
        
        
        return _rightArray.count;
        
        
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 通过判断tableView 来决定 重用标识符
    if (tableView == _leftTableView) {
        
        BQLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:left_id forIndexPath:indexPath];
        
        cell.backgroundColor = [UIColor hm_colorWithR:236 G:236 B:236];
        
        // 获取数组中的模型
        BQLeftModel *leftModel = _leftArray[indexPath.row];
        
        cell.textLabel.text = leftModel.name;
        
        return cell;
    } else {
        
        // 右侧的cell
        BQRightCell *cell = [tableView dequeueReusableCellWithIdentifier:right_id forIndexPath:indexPath];
        
        cell.selectedBackgroundView = [[UIView alloc]initWithFrame:cell.frame];
        
        cell.selectedBackgroundView.backgroundColor = [UIColor hm_colorWithR:236 G:236 B:236];
        
        BQRightModel *model = _rightArray[indexPath.row];
        
        // 为cell 传递数据
        cell.rightModel = model;
        
        return cell;
    }
}
#pragma mark
#pragma mark - 选中cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTableView) {
        
        NSDictionary *para = @{@"call" : @5};
        
        BQLeftModel *LeftModel = _leftArray[indexPath.row];
        
        FMDatabase *db = [[FMDatabase alloc] initWithPath:localDBPath];
        [db open];
        
        if (![db tableExists:@"BeeQuick"]) {
            
            [db executeUpdate:@"create table if not exists BeeQuick (id text,category_id text,name text,market_price text,partner_price text,specifics text,pm_desc text,img text,count integer)"];
            
        }
        
        FMResultSet *resultSet = [db executeQuery:@"select category_id from BeeQuick where category_id = ?",LeftModel.id];
        
        if ([resultSet next]) {
            
            FMResultSet *set = [db executeQuery:@"select * from BeeQuick where category_id = ?",LeftModel.id];
            
            
            NSMutableArray *array = [NSMutableArray array];
            while ([set next]) {
                BQRightModel *model = [[BQRightModel alloc] init];
                
                model.name = [set stringForColumn:@"name"];
                model.market_price = [set stringForColumn:@"market_price"];
                model.partner_price = [set stringForColumn:@"partner_price"];
                model.pm_desc = [set stringForColumn:@"pm_desc"];
                model.img = [set stringForColumn:@"img"];
                model.specifics = [set stringForColumn:@"specifics"];
                model.count = [set intForColumn:@"count"];
                model.category_id = [set stringForColumn:@"category_id"];
                model.id = [set stringForColumn:@"id"];
                [array addObject:model];
            }
            _rightArray = array.copy;
            
            [self.rightTableView reloadData];
            
        }else{
            
            [_AccountMgr POSTWithUrlString:supermarket_url parameters:para success:^(id responseObject) {
                
                [db open];
                
                NSArray *rightArr = responseObject[@"data"][@"products"][LeftModel.id];
                
                _rightArray = [NSArray yy_modelArrayWithClass:[BQRightModel class] json:rightArr];
                
                for (BQRightModel *model in _rightArray) {
                    
                    NSString * id = model.id;
                    
                    NSString *name = model.name;
                    
                    NSString *market_price = model.market_price;
                    
                    NSString *partner_price = model.partner_price;
                    
                    NSString *img = model.img;
                    
                    NSString *pm_desc = model.pm_desc;
                    
                    NSString *specifics = model.specifics;
                    
                    NSString *category_id = [NSString stringWithFormat:@"a%@",model.category_id];
                    
                    NSInteger count = model.count;
                    
                    [db executeUpdate:@"INSERT INTO BeeQuick(id,category_id,name,market_price,partner_price,specifics,pm_desc,img,count) VALUES(?,?,?,?,?,?,?,?,?)",id,category_id,name,market_price,partner_price,specifics,pm_desc,img,count];
                }
                
                [self.rightTableView reloadData];
                
                            [db close];
                
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
            }];
        }
        [db close];
    }
    
}



-(void)loadData{
    NSDictionary *para = @{@"call" : @5};
    
    FMDatabase *db = [[FMDatabase alloc] initWithPath:TypeDBPath];
    [db open];
    
    if (![db tableExists:@"Type"]) {
        
        
        
        [db executeUpdate:@"create table if not exists Type (id text,name text)"];
        

        
        [_AccountMgr POSTWithUrlString:supermarket_url parameters:para success:^(id responseObject) {
            
            [db open];
            
            // 获取分类模型数组
            NSArray *leftArr = responseObject[@"data"][@"categories"];
            
            _leftArray = [NSArray yy_modelArrayWithClass:[BQLeftModel class] json:leftArr];
            
            
            for (BQLeftModel *model  in _leftArray) {
                NSString *id = model.id;
                
                NSString *name = model.name;
                
                [db executeUpdate:@"INSERT INTO Type(id,name) VALUES(?,?)",id,name];
                
            }
            
            [self.leftTableView reloadData];
            
            [db close];
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        }];
        
        
        
    }else{
        
        [db open];
        
        FMResultSet *resultSet = [db executeQuery:@"select * from Type"];
        
        NSMutableArray *array = [NSMutableArray array];
        
        while ([resultSet next]) {
            BQLeftModel *model = [[BQLeftModel alloc]init];
            
            model.id = [resultSet stringForColumn:@"id"];
            
            model.name = [resultSet stringForColumn:@"name"];
            
            
            
            [array addObject:model];
        }
        
        _leftArray = array.copy;
        
        [self.leftTableView reloadData];
        
        [db close];
        
    }
    
    [db close];
    
    NSIndexPath * selIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.leftTableView selectRowAtIndexPath:selIndex animated:NO scrollPosition:UITableViewScrollPositionNone];
    [self tableView:self.leftTableView didSelectRowAtIndexPath:selIndex];
    
    
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self.rightTableView reloadData];
    
    [self.leftTableView reloadData];
    
}

@end
